from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings


def generate_openid_signature(openid):
    #对openid进行加密
    #加密后的openid
    serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=600)
    data = {'openid':openid}
    openid_sign = serializer.dumps(data)  #加密后返回的数据是bytes类型
    return openid_sign.decode()


def check_openid_sign(openid_sign):
    #对openid进行解密
    serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=600)
    try:
        data = serializer.loads(openid_sign) #解密 返回原本的数据
    except BadData:
        return None
    else:
        return data.get('openid')
